/**
 * 响应式断点 Composable
 * 统一管理应用的响应式断点逻辑
 */
import { computed, onMounted, onUnmounted, ref } from "vue"

// 断点定义（与 SCSS 变量保持一致）
export const BREAKPOINTS = {
  xs: 480,
  sm: 768,
  md: 992,
  lg: 1200,
  xl: 1440,
};

/**
 * 响应式断点 Hook
 * @returns {Object} 响应式断点状态和工具函数
 */
export function useBreakpoints() {
  const windowWidth = ref(typeof window !== "undefined" ? window.innerWidth : 1200);

  // 计算当前断点
  const currentBreakpoint = computed(() => {
    const width = windowWidth.value;
    if (width < BREAKPOINTS.xs) return "xs";
    if (width < BREAKPOINTS.sm) return "sm";
    if (width < BREAKPOINTS.md) return "md";
    if (width < BREAKPOINTS.lg) return "lg";
    return "xl";
  });

  // 响应式状态
  const isXs = computed(() => windowWidth.value < BREAKPOINTS.xs);
  const isSm = computed(() => windowWidth.value >= BREAKPOINTS.xs && windowWidth.value < BREAKPOINTS.sm);
  const isMd = computed(() => windowWidth.value >= BREAKPOINTS.sm && windowWidth.value < BREAKPOINTS.md);
  const isLg = computed(() => windowWidth.value >= BREAKPOINTS.md && windowWidth.value < BREAKPOINTS.lg);
  const isXl = computed(() => windowWidth.value >= BREAKPOINTS.lg);

  // 便捷判断
  const isMobile = computed(() => windowWidth.value < BREAKPOINTS.sm);
  const isTablet = computed(() => windowWidth.value >= BREAKPOINTS.sm && windowWidth.value < BREAKPOINTS.lg);
  const isDesktop = computed(() => windowWidth.value >= BREAKPOINTS.lg);

  // 大于等于某个断点
  const isSmAndUp = computed(() => windowWidth.value >= BREAKPOINTS.sm);
  const isMdAndUp = computed(() => windowWidth.value >= BREAKPOINTS.md);
  const isLgAndUp = computed(() => windowWidth.value >= BREAKPOINTS.lg);

  // 小于等于某个断点
  const isSmAndDown = computed(() => windowWidth.value < BREAKPOINTS.md);
  const isMdAndDown = computed(() => windowWidth.value < BREAKPOINTS.lg);

  // 处理窗口大小变化
  const handleResize = () => {
    windowWidth.value = window.innerWidth;
  };

  // 生命周期管理
  onMounted(() => {
    if (typeof window !== "undefined") {
      window.addEventListener("resize", handleResize);
    }
  });

  onUnmounted(() => {
    if (typeof window !== "undefined") {
      window.removeEventListener("resize", handleResize);
    }
  });

  return {
    // 原始数据
    windowWidth,
    currentBreakpoint,
    
    // 精确断点
    isXs,
    isSm,
    isMd,
    isLg,
    isXl,
    
    // 便捷判断
    isMobile,
    isTablet,
    isDesktop,
    
    // 范围判断
    isSmAndUp,
    isMdAndUp,
    isLgAndUp,
    isSmAndDown,
    isMdAndDown,
    
    // 工具函数
    handleResize,
  };
}